package com.software.myopiaparents.ui;


import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.king.zxing.Intents;
import com.king.zxing.util.CodeUtils;
import com.software.myopiaparents.R;
import com.software.myopiaparents.base.BaseActivity;
import com.software.myopiaparents.bean.BaseInfo;
import com.software.myopiaparents.bean.DeviceListInfo;
import com.software.myopiaparents.content.Constant;
import com.software.myopiaparents.http.HostType;
import com.software.myopiaparents.http.HttpApi2;
import com.software.myopiaparents.utils.ToastUtil;
import com.software.myopiaparents.utils.UriUtils;
import com.software.myopiaparents.utils.eb.EB;
import com.software.myopiaparents.utils.eb.EbData;
import com.software.myopiaparents.utils.perm.NetworkUtils;
import com.software.myopiaparents.utils.sp.SP;
import com.software.myopiaparents.view.dialog.CustomizeDialog;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;

import org.greenrobot.eventbus.Subscribe;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;


/**
 * 设备管理
 *
 * @author penglei
 * @date 2020/05/18
 */
public class EquipmentManageActivity extends BaseActivity {
    private static final String TAG = "EquipmentManageActivity";

    @BindView(R.id.iv_title_left)
    ImageView mIvTitleLeft;
    @BindView(R.id.tv_title_text)
    TextView mTvTitleText;
    @BindView(R.id.iv_title_right)
    ImageView mIvTitleRight;
    @BindView(R.id.lay_title_home)
    LinearLayout mLayTitleHome;

    @BindView(R.id.tv_empty_hint)
    TextView mTvEmptyHint;
    @BindView(R.id.iv_empty_image)
    ImageView mIvEmptyImage;
    @BindView(R.id.rl_empty_layout)
    RelativeLayout mRlEmptyLayout;
    @BindView(R.id.rv_list)
    RecyclerView mRvList;
    @BindView(R.id.rl_list)
    RelativeLayout mRlList;

    public static final int REQUEST_CODE_SCAN = 0X01;
    public static final int REQUEST_CODE_PHOTO = 0X02;

    private BaseQuickAdapter<DeviceListInfo.DataBean.ListBean, BaseViewHolder> mAdapter; // adapter
    private List<DeviceListInfo.DataBean.ListBean> mData = new ArrayList<>();  // 数据

    @Override
    protected int getContentViewId() {
        return R.layout.activity_equipment_manage;
    }

    @Override
    public void initView() {
        EB.register(this);
        mTvTitleText.setText(getResources().getString(R.string.s_equipment));
        mIvTitleRight.setVisibility(View.VISIBLE);

        mRvList.setLayoutManager(new LinearLayoutManager(EquipmentManageActivity.this));
        mRvList.setNestedScrollingEnabled(false);
        mRvList.setHasFixedSize(true);
        mRvList.setFocusable(false);
    }

    @Override
    public void initData() {
        getDeviceList();
    }

    @Override
    public void onDestroy() {
        EB.unregister(this);
        super.onDestroy();
    }

    @Subscribe
    public void onEvent(EbData data) {
        if (data.getType() == 10) {
            getDeviceList(); // 获取设备列表
            Log.e("=====", "=====1111");
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
    }


    @OnClick({R.id.iv_title_left, R.id.iv_title_right})
    public void onClick(final View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.iv_title_left:
                finish();
                break;

            case R.id.iv_title_right:
                getPermissions();
                break;
        }
    }


    /**
     * 检测权限
     */
    private void getPermissions() {
        AndPermission.with(this)
                .permission(Permission.CAMERA, Permission.READ_EXTERNAL_STORAGE)
                .onGranted(new Action() {
                    @Override
                    public void onAction(List<String> permissions) {
                        Log.e(TAG, "权限通过");
                        //跳转自定义扫码界面
                        Intent intent = new Intent(EquipmentManageActivity.this, ScanBindActivity.class);
                        startActivityForResult(intent, REQUEST_CODE_SCAN);
                    }
                })
                .onDenied(new Action() {
                    @Override
                    public void onAction(List<String> permissions) {
                        Uri packageURI = Uri.parse("package:" + getPackageName());
                        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                        ToastUtil.showShort("没有权限无法扫描呦");
                    }
                }).start();
    }


    /**
     * 设备列表
     */
    private void getDeviceList() {
        String jwt_token = new SP().load(Constant.USER_JWT_TOKEN, "");
        if (NetworkUtils.isConnected(EquipmentManageActivity.this)) {
            Map<String, String> headers = new HashMap<>();
            headers.put("Authorization", jwt_token);

            HttpApi2.getApiService(HostType.TELE_CONFIG).getDeviceList(headers).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Subscriber<DeviceListInfo>() {
                        @Override
                        public void onSubscribe(Subscription s) {
                            s.request(Long.MAX_VALUE);
                        }

                        @Override
                        public void onNext(DeviceListInfo deviceListInfo) {
                            try {
                                Log.e(TAG, "===deviceListInfo:" + deviceListInfo.toString());
                                if (deviceListInfo.getCode().equals(Constant.CODE_SUCCESS)) {
                                    mData = deviceListInfo.getData().getList();
                                    if (deviceListInfo.getData() != null && deviceListInfo.getData().getList().size() > 0) {
                                        mRlEmptyLayout.setVisibility(View.GONE);
                                    } else {
                                        mRlEmptyLayout.setVisibility(View.VISIBLE);
                                    }
                                    setAdapter();
                                } else {
                                    ToastUtil.showShort(deviceListInfo.getMsg());
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onError(Throwable t) {

                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        } else {
            ToastUtil.showShort(getResources().getString(R.string.network_fial_message));
        }
    }


    /**
     * 列表适配器
     */
    private void setAdapter() {
        mRvList.setAdapter(mAdapter = new BaseQuickAdapter<DeviceListInfo.DataBean.ListBean, BaseViewHolder>(R.layout.item_equipment_list, mData) {
            @Override
            protected void convert(BaseViewHolder helper, DeviceListInfo.DataBean.ListBean item) {
                LinearLayout lay_list = helper.getView(R.id.lay_list);
                ImageView iv_close = helper.getView(R.id.iv_close);
                ImageView iv_edit = helper.getView(R.id.iv_edit);
                TextView tv_device_number = helper.getView(R.id.tv_device_number);
                TextView tv_name = helper.getView(R.id.tv_name);

                try {
                    tv_device_number.setText(item.getDevice_code());
                    if (!TextUtils.isEmpty(item.getName())) {
                        tv_name.setText(item.getName());
                    } else {
                        tv_name.setText(getResources().getString(R.string.s_unknown_number));
                    }

//                    getCustomer(item.getPhone(), helper.getLayoutPosition(), mCustomerType, lay_list);

                    // 删除
                    iv_close.setOnClickListener(v -> {
                        deleteDeviceDialog(item.getDevice_code(), helper.getLayoutPosition());
                    });

                    // 编辑
                    iv_edit.setOnClickListener(v -> {
                        inputDevicenameDialog(item.getBinding_id(), helper.getLayoutPosition());
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });
    }

    /**
     * 删除设备弹框（解绑设备）
     */
    private void deleteDeviceDialog(String device_code, int position) {
        final CustomizeDialog dialog = new CustomizeDialog(EquipmentManageActivity.this, R.style.DialogUtilStyle);
        dialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialogInterface) {
                TextView tv_title = (TextView) dialog.findViewById(R.id.tv_title);
                TextView tv_content = (TextView) dialog.findViewById(R.id.tv_content);
                TextView tv_cancel = (TextView) dialog.findViewById(R.id.tv_cancel);
                TextView tv_confirm = (TextView) dialog.findViewById(R.id.tv_confirm);

                //取消
                tv_cancel.setOnClickListener(v -> {
                    dialog.dismiss();
                });

                //删除
                tv_confirm.setOnClickListener(v -> {
                    getUnBindDevice(device_code, position);
                    dialog.dismiss();
                });
            }
        });
        dialog.showDialog(R.layout.dialog_device_delete);
    }


    /**
     * 修改设备名称弹框
     */
    private void inputDevicenameDialog(int binding_id, int position) {
        final CustomizeDialog dialog = new CustomizeDialog(EquipmentManageActivity.this, R.style.DialogUtilStyle);
        dialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialogInterface) {
                EditText et_change_nickname_input = (EditText) dialog.findViewById(R.id.et_change_nickname_input);
                Button btn_confirm = (Button) dialog.findViewById(R.id.btn_confirm);
                ImageView iv_close = (ImageView) dialog.findViewById(R.id.iv_close);

                //取消
                iv_close.setOnClickListener(v -> {
                    dialog.dismiss();
                });

                //确认
                btn_confirm.setOnClickListener(v -> {

                    String devicename = et_change_nickname_input.getText().toString().trim();
                    //验证设备名称
                    if (TextUtils.isEmpty(devicename)) {
                        ToastUtil.showShort(getString(R.string.toast_devicename_empty));
                        return;
                    }
                    getEditDeviceNameDevice(devicename, binding_id, position);
                    dialog.dismiss();
                });
            }
        });
        dialog.showDialog(R.layout.dialog_change_nickname);
    }

    /**
     * 修改设备名
     */
    private void getEditDeviceNameDevice(String name, int binding_id, int position) {
        String jwt_token = new SP().load(Constant.USER_JWT_TOKEN, "");
        if (NetworkUtils.isConnected(EquipmentManageActivity.this)) {
            Map<String, String> headers = new HashMap<>();
            headers.put("Authorization", jwt_token);

            Map<String, String> params = new HashMap<>();
            params.put("binding_id", binding_id + "");
            params.put("name", name);

            HttpApi2.getApiService(HostType.TELE_CONFIG).getEditDeviceName(headers, params).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Subscriber<BaseInfo>() {
                        @Override
                        public void onSubscribe(Subscription s) {
                            s.request(Long.MAX_VALUE);
                        }

                        @Override
                        public void onNext(BaseInfo baseInfo) {
                            try {
                                Log.e(TAG, "===baseInfo:" + baseInfo.toString());
                                if (baseInfo.getCode().equals(Constant.CODE_SUCCESS)) {
                                    ToastUtil.showShort(baseInfo.getMsg());
                                    getDeviceList();
                                } else {
                                    ToastUtil.showShort(baseInfo.getMsg());
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onError(Throwable t) {

                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        } else {
            ToastUtil.showShort(getResources().getString(R.string.network_fial_message));
        }
    }

    /**
     * 解绑设备
     */
    private void getUnBindDevice(String device_code, int position) {
        String jwt_token = new SP().load(Constant.USER_JWT_TOKEN, "");
        if (NetworkUtils.isConnected(EquipmentManageActivity.this)) {
            Map<String, String> headers = new HashMap<>();
            headers.put("Authorization", jwt_token);

            Map<String, String> params = new HashMap<>();
            params.put("device_code", device_code);

            HttpApi2.getApiService(HostType.TELE_CONFIG).getUnBindDevice(headers, params).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Subscriber<BaseInfo>() {
                        @Override
                        public void onSubscribe(Subscription s) {
                            s.request(Long.MAX_VALUE);
                        }

                        @Override
                        public void onNext(BaseInfo baseInfo) {
                            try {
                                Log.e(TAG, "===baseInfo:" + baseInfo.toString());
                                if (baseInfo.getCode().equals(Constant.CODE_SUCCESS)) {
                                    ToastUtil.showShort(baseInfo.getMsg());
                                    mData.remove(position);
                                    mAdapter.notifyItemRemoved(position);
                                    getDeviceList();
                                } else {
                                    ToastUtil.showShort(baseInfo.getMsg());
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onError(Throwable t) {

                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        } else {
            ToastUtil.showShort(getResources().getString(R.string.network_fial_message));
        }
    }

    /**
     * 绑定设备
     */
    private void getBindDevice(String device_code) {
        String jwt_token = new SP().load(Constant.USER_JWT_TOKEN, "");
        if (NetworkUtils.isConnected(EquipmentManageActivity.this)) {
            Map<String, String> headers = new HashMap<>();
            headers.put("Authorization", jwt_token);

            Map<String, String> params = new HashMap<>();
            params.put("device_code", device_code);

            HttpApi2.getApiService(HostType.TELE_CONFIG).getBindDevice(headers, params).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Subscriber<BaseInfo>() {
                        @Override
                        public void onSubscribe(Subscription s) {
                            s.request(Long.MAX_VALUE);
                        }

                        @Override
                        public void onNext(BaseInfo baseInfo) {
                            try {
                                Log.e(TAG, "===baseInfo:" + baseInfo.toString());
                                if (baseInfo.getCode().equals(Constant.CODE_SUCCESS)) {
                                    ToastUtil.showShort(baseInfo.getMsg());
                                    getDeviceList();
                                } else {
                                    ToastUtil.showShort(baseInfo.getMsg());
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onError(Throwable t) {

                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        } else {
            ToastUtil.showShort(getResources().getString(R.string.network_fial_message));
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && data != null) {
            switch (requestCode) {
                case REQUEST_CODE_SCAN:
                    String result = data.getStringExtra(Intents.Scan.RESULT);
                    Toast.makeText(this, result, Toast.LENGTH_SHORT).show();
                    //验证设备号
                    if (TextUtils.isEmpty(result)) {
                        ToastUtil.showShort(getString(R.string.toast_devicenum_empty));
                        return;
                    }
                    getBindDevice(result);
                    break;
                case REQUEST_CODE_PHOTO:
                    parsePhoto(data);
                    break;
            }

        }
    }

    private void asyncThread(Runnable runnable) {
        new Thread(runnable).start();
    }

    /**
     * 识别图片
     *
     * @param data
     */
    private void parsePhoto(Intent data) {
        final String path = UriUtils.getImagePath(this, data);
        Log.d("Jenly", "path:" + path);
        if (TextUtils.isEmpty(path)) {
            return;
        }
        //异步解析
        asyncThread(new Runnable() {
            @Override
            public void run() {
                final String result = CodeUtils.parseCode(path);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.d("Jenly", "result:" + result);
                        Toast.makeText(EquipmentManageActivity.this, result, Toast.LENGTH_SHORT).show();
                    }
                });

            }
        });

    }


}
